package com.sh.d1.gatewayserver;

import com.alibaba.fastjson.JSONObject;
import com.sh.d1.gatewayserver.router.RouterHandler;
import io.netty.channel.*;
import com.sh.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

/**
 * 客户端消息处理器
 */
public class ClientMsgHandler extends ChannelInboundHandlerAdapter {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(ClientMsgHandler.class);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {

        ChannelPipeline pl = ctx.pipeline();
        if (null == pl.get(ValidateUserIdHandler.class)) {
            pl.addBefore(ctx.name(),
                    ValidateUserIdHandler.class.getName(),
                    new ValidateUserIdHandler());
        }

        if (null == pl.get(RouterHandler.class)) {
            pl.addAfter(ctx.name(),
                    RouterHandler.class.getName(),
                    new RouterHandler());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

        // 获取客户端信道
        Channel ch = ctx.channel();

        // 设置会话 Id 并添加到分组
        IdSetterGetter.setSessionId(ch);
        ClientChannelGroup.add(ch);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel ch = ctx.channel();
        ClientChannelGroup.remove(ch);

        int userId = IdSetterGetter.getUserId(ch);

        try (Jedis redis = RedisUtil.getRedis()) {
            if (redis == null) {
                return;
            }
//            String serverId = redis.hget("User_" + userId, "AtGatewayServerId");
//
//            if (serverId.equals(GatewayServer.getId())) {
//                redis.hdel("User_" + userId, "AtGatewayServerId");
//            }
            String luaScript = "local key_user_N=\"User_\"  ..KEYS[1]\n" +
                    "local field_AtGatewayServerId=\"AtGatewayServerId\"\n" +
                    "local key_GatewayServer_N=\"GatewayServer_\" ..KEYS[2]\n" +
                    "local val_GatewayServerId=KEYS[2]\n" +
                    "local val=redis.call(\"hget\",key_user_N,field_AtGatewayServerId)\n" +
                    "if(val == val_GatewayServerId) then\n" +
                    "    redis.call(\"hdel\",key_user_N,field_AtGatewayServerId)\n" +
                    "    redis.call(\"hdel\",key_GatewayServer_N,key_user_N)\n" +
                    "    return 1\n" +
                    "end\n" +
                    "return 0";

            redis.eval(luaScript, 2,
                    String.valueOf(userId),  //KEYS[1]
                    GatewayServer.getId());    //KEYS[2]

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("gatewayServerId", GatewayServer.getId());
            jsonObj.put("remoteSessionId", IdSetterGetter.getSessionId(ch));
            jsonObj.put("userId", userId);

            String jsonStr = jsonObj.toJSONString();
            redis.publish("UserOffline", jsonStr);
            LOGGER.info("用户离线,msg={}", jsonStr);

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
        }
    }

}
